package fv;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import de.svenjacobs.loremipsum.LoremIpsum;

/**
 * Servlet implementation class comments
 */
public class comments extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public JSONObject json = new JSONObject();
	JSONArray jsonArr = new JSONArray();
	int retcnt = 25;
	String outfitid = null;
	String sqlstr = null;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public comments() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		outfitid = request.getParameter("id");
		sqlstr = "select * from comments where photoid = " + outfitid
				+ " order by commid desc limit " + retcnt;
		System.out.println(sqlstr);
		List<String> cmts = OutfitsDatabase.getComments(Integer
				.parseInt(outfitid));
		for (String c : cmts) {
			jsonArr.add(c);
		}
		// Connection conn = mysqlconn.getConn();
		// json.clear();
		// try {
		// Statement s = conn.createStatement();
		// s.executeQuery(sqlstr);
		// ResultSet rs = s.getResultSet();
		//
		// while (rs.next())
		// {
		// json.put("comment", rs.getString(3));
		// jsonArr.add(json);
		// }
		//
		// rs.close();
		// s.close();
		// }
		// catch(Exception e)
		// {
		// System.out.println(e.getMessage());
		// }
		// mysqlconn.closeConn(conn);
		response.setContentType("application/json");
		response.getWriter().write(jsonArr.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String comments = request.getParameter("comment");
		outfitid = request.getParameter("id");
		sqlstr = "insert into comments(photoid, content) values(" + outfitid
				+ ", '" + comments + "')";
		System.out.println(sqlstr);
		OutfitsDatabase.comment(Integer.parseInt(outfitid),
				URLDecoder.decode(comments));
		// Connection conn = mysqlconn.getConn();
		// if (conn != null) {
		// try {
		// Statement s = conn.createStatement();
		// s.execute(sqlstr);
		// s.close();
		// } catch (Exception e) {
		// System.out.println(e.getMessage());
		// }
		// }
		// mysqlconn.closeConn(conn);
	}

}
